package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.StrategyCatalog;
import cn.wolfcode.wolf2w.query.StrategyCatalogQuery;
import cn.wolfcode.wolf2w.repository.StrategyCatalogRepository;
import cn.wolfcode.wolf2w.repository.StrategyRepository;
import cn.wolfcode.wolf2w.service.IStrategyCatalogService;
import cn.wolfcode.wolf2w.util.DBHelper;
import cn.wolfcode.wolf2w.vo.CatalogVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class StrategyCatalogServiceImpl implements IStrategyCatalogService {


    @Autowired
    private StrategyCatalogRepository strategyCatalogRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private StrategyRepository strategyRepository;


    @Override
    public void insert(StrategyCatalog strategyCatalog) {
        strategyCatalogRepository.insert(strategyCatalog);
    }

    @Override
    public void delete(String id) {
        strategyCatalogRepository.deleteById(id);
    }

    @Override
    public void update(StrategyCatalog strategyCatalog) {
        strategyCatalogRepository.save(strategyCatalog);
    }

    @Override
    public StrategyCatalog get(String id) {
        //orElse方法从optional中取值，如果取不到返回null
        return strategyCatalogRepository.findById(id).orElse(null);
    }

    @Override
    public List<StrategyCatalog> list() {
        return strategyCatalogRepository.findAll();
    }

    @Override
    public Page<StrategyCatalog> query(StrategyCatalogQuery qo) {
//        //原始代码
//        Query query = new Query();
//        long totalcount = mongoTemplate.count(query, StrategyCatalog.class);
//        if(totalcount == 0){
//            //没有数据
//            return Page.empty();
//        }
//        Pageable pageable = PageRequest.of(qo.getCurrentPage()-1, qo.getPageSize(), Sort.Direction.ASC, "_id");
//        query.with(pageable);
//        List<StrategyCatalog> list = mongoTemplate.find(query, StrategyCatalog.class);
//        Page<StrategyCatalog> page =  new PageImpl<>(list, pageable, totalcount);
//        return page;
        return DBHelper.query(mongoTemplate, StrategyCatalog.class, qo, null);
    }

    @Override
    public void saveOrUpdate(StrategyCatalog strategyCatalog) {
        System.out.println(strategyCatalog.getId());
        if(!StringUtils.hasLength(strategyCatalog.getId())){
            //防止id为空串，直接写入到数据库，导致自动生成_id不成功
            strategyCatalog.setId(null);
            strategyCatalogRepository.save(strategyCatalog);
        }
        else{
            strategyCatalogRepository.save(strategyCatalog);
        }
    }

    @Override
    public void changeHotValue(String id, Integer hot) {
        //能实现功能，但是需要发送两次数据库请求
//        StrategyCatalog strategyCatalog = strategyCatalogRepository.findById(id).orElse(null);
//        strategyCatalog.setIshot(hot);
//        strategyCatalogRepository.save(strategyCatalog);

        //方案二
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        Update update = new Update();
        update.set("ishot", hot);
        mongoTemplate.updateMulti(query,update,StrategyCatalog.class);

    }

    @Override
    public List<CatalogVO> queryCatalogVO() {

        //创建分组查询对象
        TypedAggregation<StrategyCatalog> agg =  Aggregation.newAggregation(StrategyCatalog.class,
                Aggregation.group("destName").
                        push("name").as("names").
                        push("id").as("ids")
                );
        AggregationResults<Map> result =  mongoTemplate.aggregate(agg, Map.class);
        List<Map> datas = result.getMappedResults();
        //页面中药使用的数据类型
        List<CatalogVO> list = new ArrayList<>();
        for (Map data : datas) {
            CatalogVO vo = new CatalogVO();
            vo.setDestName(data.get("_id").toString());
            List<Object> names = (List<Object>) data.get("names");
            List<Object> ids = (List<Object>) data.get("ids");
            List<StrategyCatalog> catalogList = new ArrayList<>();
            for(int i=0; i<names.size(); i++){
                StrategyCatalog sc = new StrategyCatalog();
                String name = names.get(i).toString();
                String id = ids.get(i).toString();
                sc.setName(name);
                sc.setId(id);
                catalogList.add(sc);
            }
            vo.setCatalogList(catalogList);
            list.add(vo);
        }



        return list;
    }

    @Override
    public List<StrategyCatalog> catalogs(String destId) {
        List<StrategyCatalog> list = strategyCatalogRepository.findByDestId(destId);
        for (StrategyCatalog strategyCatalog : list) {
            //根据攻略id查询所有攻略
            List<Strategy> strategyList = strategyRepository.findByCatalogId(strategyCatalog.getId());
            //将攻略列表存储到攻略分类中
            strategyCatalog.setStrategies(strategyList);
        }
        return list;
    }

}
